<template>
    <div ref="map" style="width: 100vw;height:40vh"></div>
    <el-button @click="mapScreenshot">地图截图</el-button>
    <el-button @click="mapScreenshotToWorkbook">地图截图至表格</el-button>
    <el-button @click="downloadWorkbook">下载表格</el-button>
    <el-table :data="tableData" border>
        <el-table-column v-for="(item,index) in field" :key="index">
            <template #header>
                {{ item }}
            </template>
            <template #default="scope">
                <div v-if="index < 1 || index > 2">
                    {{ scope.row[index] }}
                </div>
                <div v-else>
                    <el-image :src="scope.row[index]"
                              :preview-src-list="[[scope.row[index]]]"
                              fit="contain"></el-image>
                </div>
            </template>
        </el-table-column>
    </el-table>
</template>

<script>
import * as Excel       from "exceljs";
import {onMounted, ref} from "vue"
import {downloadBlob}   from "@/utils/utils";
import html2canvas from "html2canvas"
export default {
    name: 'Excel',
    props: {
        msg: String,
    },
    setup() {
        let map = ref();
        onMounted(()=>{
            // 百度地图API功能
            let bmap = new BMap.Map(map.value);    // 创建Map实例
            bmap.centerAndZoom(new BMap.Point(116.404, 39.915), 11);  // 初始化地图,设置中心点坐标和地图级别
            bmap.setCurrentCity("北京");          // 设置地图显示的城市 此项是必须设置的
            bmap.enableScrollWheelZoom(true);     //开启鼠标滚轮缩放
        })

        const workbook = new Excel.Workbook();
        console.log("workbook", workbook)
        let readImg = (img) => {
            let buffer = workbook.getImage(img.imageId).buffer
            let array = [...new Uint8Array(buffer)]
            let str = '';
            let chunk = 8 * 1024;
            let i = 0;
            for (; i < array.length / chunk; i++) {
                str += String.fromCharCode.apply(null, array.slice(i * chunk, (i + 1) * chunk));
            }
            str += String.fromCharCode.apply(null, array.slice(i * chunk));
            return "data:image/jpeg;base64," + window.btoa(str)
        }
        let data = ref([])
        let field = ref([])
        let tableData = ref([])

        fetch("/excel/output.xlsx").then(resp => {
            return resp.arrayBuffer()
        }).then(async buffer => {
            console.log(workbook)
            await workbook.xlsx.load(buffer)
            console.log(workbook.worksheets)
            workbookToTable()
        })

        function workbookToTable(){
            workbook.eachSheet(((worksheet, id) => {
                console.log("工作表 " + worksheet.name, worksheet, id)
                let sheetValues = worksheet.getSheetValues()
                let images = worksheet.getImages()
                for (let i = 0; i < images.length; i++) {
                    let img = images[i]
                    let b64img = readImg(img)
                    let col = img.range.tl.nativeCol
                    let row = img.range.tl.nativeRow
                    console.log(img,img.range)
                    try {
                        console.log(sheetValues[row + 1][col + 1], row, col)
                        sheetValues[row + 1][col + 1] = b64img
                    } catch(e) {
                        console.log(e)
                    }
                }

                data.value = Array.from(sheetValues)
                data.value.shift()
                data.value.forEach((item) => {
                    item.shift()
                })
                console.log(data)
                field.value = data.value[0]
                tableData.value = data.value.slice(1)
                console.log(field.value, tableData.value)
            }))
        }
        return {
            map,
            data,
            field,
            tableData,
            downloadWorkbook(){
                workbook.xlsx.writeBuffer().then((buffer)=>{
                    let fileBlob = new Blob([buffer])
                    downloadBlob("测试.xlsx", fileBlob)
                })
            },
            mapScreenshot(){
                html2canvas(map.value,{
                    allowTaint: true,
                    useCORS: true,
                }).then(canvas=>{
                    canvas.toBlob((blob)=>{
                        downloadBlob("截图.jpg",blob)
                    })
                })
            },
            mapScreenshotToWorkbook(){
                html2canvas(map.value,{
                    allowTaint: true,
                    useCORS: true,
                }).then(canvas=>{
                    canvas.toBlob((blob)=>{
                        let reader = new FileReader();
                        reader.addEventListener("load",(e)=>{
                            let imageId = workbook.addImage({
                                buffer: e.target.result,
                                extension: "jpeg"
                            })
                            let row = 1
                            let col = 1
                            let worksheet = workbook.getWorksheet("p7000")
                            worksheet.getCell(row + 1,col + 1).value = undefined
                            worksheet.getImages().filter((imageMedia)=>{
                                // 图片所在范围
                                let range = imageMedia.range
                                // 图片左上角
                                let topLeft = range.tl
                                // 图片左上角 原始 所在行号列号与目标相同
                                return topLeft.nativeRow === row && topLeft.nativeCol === col
                            }).forEach(imageMedia=>{
                                let media = worksheet._media
                                // 图片所在范围
                                let range = imageMedia.range

                                worksheet._media = media.filter(media => {
                                    let condition = media.imageId === imageMedia.imageId
                                    if (media.range.tr && range.tl) {
                                        condition = condition &&
                                            media.range.tl.nativeRow === range.tl.nativeRow &&
                                            media.range.tl.nativeRowOff === range.tl.nativeRowOff &&
                                            media.range.tl.nativeCol === range.tl.nativeCol &&
                                            media.range.tl.nativeColOff === range.tl.nativeColOff
                                    } else {
                                        return true
                                    }

                                    if (media.range.br && range.br) {
                                        condition = condition &&
                                            media.range.br.nativeRow === range.br.nativeRow &&
                                            media.range.br.nativeRowOff === range.br.nativeRowOff &&
                                            media.range.br.nativeCol === range.br.nativeCol &&
                                            media.range.br.nativeColOff === range.br.nativeColOff
                                    } else {
                                        return true
                                    }

                                    return !condition
                                })
                                console.log("worksheet._media",worksheet._media)
                            })
                            const cellRow = worksheet.getRow(row + 1);
                            cellRow.width = 25
                            let cellCol = worksheet.getColumn(col + 1);
                            cellCol.width = 50

                            worksheet.addImage(imageId, {
                                tl: {
                                    row: 1,
                                    col: 1
                                },
                                ext:
                                    {
                                        width: 90 * (96/50),
                                        height: 30 * (96/25)
                                    }
                            });
                            workbookToTable()

                        })
                        reader.readAsArrayBuffer(blob);
                    })
                })
            }
        }
    },
}
</script>

<style scoped>
h3 {
    margin: 40px 0 0;
}

ul {
    list-style-type: none;
    padding: 0;
}

li {
    display: inline-block;
    margin: 0 10px;
}

a {
    color: #42b983;
}
</style>
